<template>
  <header class="header">
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
      <div class="container header-container">
        <!-- 左侧：系统Logo和名称 -->
        <div class="header-left">
          <router-link class="navbar-brand" to="/">
            <span class="logo-icon"></span>
            <span class="system-name">日霄门户</span>
          </router-link>
        </div>

        <!-- 中间：搜索框 -->
        <div class="header-search">
          <div class="search-box">
            <input 
              type="text" 
              class="search-input" 
              placeholder="搜索内容..."
              v-model="searchQuery"
              @keyup.enter="performSearch"
            >
            <button class="search-btn" @click="performSearch">
              <i class="icon-search"></i>
            </button>
          </div>
        </div>

        <!-- 右侧：导航菜单和用户区域 -->
        <div class="header-right">
          <!-- 主导航菜单 -->
          <div class="collapse navbar-collapse main-menu-container">
            <ul class="navbar-nav main-menu">
              <li>
                <a 
                  class="nav-link" 
                  href="/home"
                >
                  首页
                </a>
              </li>
              <li class="nav-item" v-for="category in topCategories" :key="category.categoryId">
                
                <router-link 
                  
                  class="nav-link" 
                  :to="`/category/${category.categoryId}`"
                >
                  {{ category.categoryName }}
                </router-link>
              </li>
            </ul>
          </div>

          <!-- 用户菜单 -->
          <ul class="navbar-nav user-menu">
            <template v-if="!isAuthenticated">
              <li class="nav-item">
                <router-link class="nav-link login-btn" to="/login">
                  <i class="icon-user"></i>登录
                </router-link>
              </li>
              <li class="nav-item">
                <router-link class="nav-link register-btn" to="/register">
                  <i class="icon-edit"></i>注册
                </router-link>
              </li>
            </template>
            <template v-else>
              <li class="nav-item user-menu-item">
                <div class="user-profile-container">
                  <a class="nav-link user-profile" href="#" @mouseenter="showDropdown = true" @mouseleave="showDropdown = false">
                    <span class="username">{{ safeCurrentUser.nickname || safeCurrentUser.username || '用户' }}</span>
                    <div class="user-avatar-wrapper">
                      <img v-if="safeCurrentUser.avatar" :src="safeCurrentUser.avatar" class="user-avatar" alt="用户头像">
                      <div v-else class="avatar-placeholder">
                        {{ (safeCurrentUser.nickname || safeCurrentUser.username || '用户').charAt(0) }}
                      </div>
                    </div>
                  </a>
                  
                  <transition name="fade">
                    <div 
                      class="dropdown-menu user-dropdown" 
                      v-show="showDropdown"
                      @mouseenter="showDropdown = true"
                      @mouseleave="showDropdown = false"
                    >
                      <router-link class="dropdown-item" to="/user/center">
                        <i class="icon-user"></i>个人中心
                      </router-link>
                      <router-link class="dropdown-item" to="/user/posts">
                        <i class="icon-file"></i>我的文章
                      </router-link>
                      <div class="dropdown-divider"></div>
                      <a class="dropdown-item logout-item" href="#" @click.prevent="logout">
                        <i class="icon-logout"></i>退出登录
                      </a>
                    </div>
                  </transition>
                </div>
              </li>
            </template>
          </ul>

          <!-- 移动端菜单按钮 -->
          <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".main-menu-container">
            <span class="navbar-toggler-icon"></span>
          </button>
        </div>
      </div>
    </nav>
  </header>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'
import { getCategoryList } from '@/api/category'

export default {
  name: 'Header',
  data() {
    return {
      topCategories: [],
      searchQuery: '',
      showDropdown: false
    } 
  },
  mounted() {
  window.addEventListener('scroll', this.handleScroll)
},
computed: {
    ...mapGetters('user', {
    isAuthenticated: 'isAuthenticated',
    currentUser: 'currentUser'
  }),
    safeCurrentUser() {
    // 双重防护
    return (this.currentUser && typeof this.currentUser === 'object') 
      ? this.currentUser 
      : {}
  }
    
  },
beforeDestroy() {
  window.removeEventListener('scroll', this.handleScroll)
},
  
  created() {
    this.fetchTopCategories()
  },
  methods: {
    ...mapActions('user',['logout']),
    async fetchTopCategories() {
      try {
        const res = await getCategoryList({ parentId: 0, visible: '0' })
        this.topCategories = res.data
      } catch (error) {
        console.error('获取顶级栏目失败:', error)
      }
    },
     handleScroll() {
      const header = document.querySelector('.header')
      if (window.scrollY > 10) {
        header.classList.add('scrolled')
      } else {
        header.classList.remove('scrolled')
      }
    },
    performSearch() {
      if (this.searchQuery.trim()) {
        this.$router.push({ path: '/search', query: { q: this.searchQuery } })
        this.searchQuery = ''
      }
    },
    handleLinkClick(category) {
      if (category.linkUrl.startsWith('http')) {
        // 外部链接直接跳转
        window.open(category.link, '_blank')
      } else {
        // 内部链接使用路由跳转
        this.$router.push(category.link)
      }
    }
  }
}
</script>
<style scoped>
/* 基础重置 */
ul, li {
  list-style: none;
  padding: 0;
  margin: 0;
}

/* 整体布局 */
.header {
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  background: #fff;
  position: sticky;
  top: 0;
  z-index: 1000;
}

.header-container {
  display: flex;
  align-items: center;
  padding: 0 15px;
  height: 60px;
}

/* 左侧Logo区域 */
.header-left {
  display: flex;
  align-items: center;
  margin-right: 30px;
}

.navbar-brand {
  display: flex;
  align-items: center;
  text-decoration: none;
}

.logo-icon {
  display: inline-block;
  width: 30px;
  height: 30px;
  background: #3498db;
  border-radius: 4px;
  margin-right: 10px;
}

.system-name {
  font-weight: 700;
  font-size: 1.5rem;
  color: #2c3e50;
  white-space: nowrap;
}

/* 搜索框样式 */
.header-search {
  flex: 1;
  max-width: 500px;
  margin: 0 20px;
}

.search-box {
  position: relative;
  display: flex;
  align-items: center;
}

.search-input {
  width: 100%;
  padding: 8px 15px;
  padding-right: 40px;
  border: 1px solid #ddd;
  border-radius: 20px;
  outline: none;
  transition: all 0.3s;
}

.search-input:focus {
  border-color: #3498db;
  box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
}

.search-btn {
  position: absolute;
  right: 10px;
  background: none;
  border: none;
  color: #777;
  cursor: pointer;
  outline: none;
}

.search-btn:hover {
  color: #3498db;
}

/* 右侧区域 */
.header-right {
  display: flex;
  align-items: center;
  margin-left: auto;
}

/* 主导航菜单 */
.main-menu-container {
  display: flex;
}

.main-menu {
  display: flex;
  align-items: center;
}

.main-menu .nav-item {
  margin: 0 5px;
}

.main-menu .nav-link {
  padding: 10px 15px;
  color: #555;
  font-weight: 500;
  text-decoration: none;
  transition: all 0.3s;
  border-radius: 4px;
}

.main-menu .nav-link:hover,
.main-menu .nav-link.router-link-exact-active {
  color: #3498db;
  background: rgba(52, 152, 219, 0.05);
}

/* 用户菜单 */
.user-menu {
  display: flex;
  align-items: center;
  margin-left: 20px;
}

.login-btn,
.register-btn {
  padding: 6px 12px !important;
  border-radius: 4px;
  transition: all 0.3s;
  text-decoration: none;
}

.login-btn {
  color: #555;
}

.login-btn:hover {
  color: #3498db;
}

.register-btn {
  background: #3498db;
  color: white !important;
  margin-left: 10px;
}

.register-btn:hover {
  background: #2980b9;
}

.user-profile {
  display: flex;
  align-items: center;
  padding: 5px 10px !important;
  text-decoration: none;
}

.user-avatar {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  margin-right: 8px;
  object-fit: cover;
}

.username {
  max-width: 120px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 下拉菜单 */
.dropdown-menu {
  border: none;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  padding: 5px 0;
  min-width: 180px;
}

.dropdown-item {
  padding: 8px 15px;
  color: #555;
  text-decoration: none;
  display: flex;
  align-items: center;
}

.dropdown-item i {
  margin-right: 10px;
  width: 18px;
  text-align: center;
}

.dropdown-item:hover {
  background: rgba(52, 152, 219, 0.1);
  color: #3498db;
}

.dropdown-divider {
  height: 1px;
  background: #eee;
  margin: 5px 0;
}

/* 响应式设计 */
@media (max-width: 992px) {
  .header-container {
    flex-wrap: wrap;
    height: auto;
    padding: 10px 15px;
  }
  
  .header-left {
    order: 1;
    margin-right: auto;
  }
  
  .header-search {
    order: 3;
    width: 100%;
    max-width: 100%;
    margin: 15px 0 10px;
  }
  
  .header-right {
    order: 2;
    margin-left: 0;
  }
  
  .main-menu-container {
    position: fixed;
    top: 70px;
    left: 0;
    right: 0;
    background: white;
    box-shadow: 0 5px 10px rgba(0, 0, 0, 0.1);
    padding: 15px;
    z-index: 999;
    max-height: calc(100vh - 70px);
    overflow-y: auto;
  }
  
  .main-menu {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .main-menu .nav-item {
    width: 100%;
    margin: 0;
  }
  
  .main-menu .nav-link {
    display: block;
    padding: 10px 0 !important;
    border-bottom: 1px solid #eee;
  }
  
  .user-menu {
    margin-left: 15px;
  }
}

@media (max-width: 576px) {
  .system-name {
    font-size: 1.2rem;
  }
  
  .login-btn,
  .register-btn {
    padding: 5px 8px !important;
    font-size: 0.9rem;
  }
}

/* 用户菜单容器 */
.user-menu-item {
  position: relative;
  margin-left: 15px;
}

.user-profile-container {
  position: relative;
  height: 100%;
}

/* 用户头像区域 */
.user-profile {
  display: flex;
  align-items: center;
  padding: 0 10px !important;
  height: 100%;
  text-decoration: none;
  color: #2c3e50;
  transition: all 0.2s ease;
}

.user-profile:hover {
  background-color: rgba(52, 152, 219, 0.1);
}

/* 用户名 */
.username {
  margin-right: 8px;
  font-weight: 500;
  white-space: nowrap;
}

/* 用户头像容器 */
.user-avatar-wrapper {
  width: 36px;
  height: 36px;
}

/* 用户头像 */
.user-avatar {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #fff;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

/* 头像占位符 */
.avatar-placeholder {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background-color: #3498db;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 16px;
  border: 2px solid #fff;
}

/* 下拉菜单 */
.user-dropdown {
  position: absolute;
  right: 0;
  top: 100%;
  min-width: 160px;
  background: white;
  border-radius: 4px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  padding: 8px 0;
  margin-top: 5px;
}

/* 下拉菜单项 */
.dropdown-item {
  display: flex;
  align-items: center;
  padding: 8px 16px;
  color: #2c3e50;
  text-decoration: none;
  transition: all 0.2s ease;
  font-size: 14px;
}

.dropdown-item i {
  width: 20px;
  margin-right: 10px;
  text-align: center;
  color: #7f8c8d;
}

.dropdown-item:hover {
  background-color: #f8f9fa;
  color: #3498db;
}

.dropdown-item:hover i {
  color: #3498db;
}

/* 退出登录项 */
.logout-item {
  color: #e74c3c !important;
}

.logout-item i {
  color: #e74c3c !important;
}

.logout-item:hover {
  background-color: #fef0f0 !important;
}

/* 下拉分割线 */
.dropdown-divider {
  margin: 5px 0;
  border-color: #eee;
}

/* 过渡动画 */
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.2s ease;
}
.fade-enter, .fade-leave-to {
  opacity: 0;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .username {
    display: none;
  }
  
  .user-avatar-wrapper {
    width: 32px;
    height: 32px;
  }
  
  .user-dropdown {
    right: -10px;
  }
}
</style>